package com.bj.disc.service;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.ai3d.rfid.common.log.Logcat;
import com.alibaba.fastjson.JSON;
import com.bj.disc.bean.MessageResponse;
import com.ym521.logdog.LogDog;


import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class WebSocketInstance {
    //连接地址
    private String TAG = WebSocketInstance.this.getClass().getSimpleName();
    private String key = "QyMxjdo8alBIxSxtg5Su0bIIKMK7bz0D";
    private volatile static WebSocketInstance instance;
    private OkHttpClient mClient;
    private Request request;
    private WebSocket webSocket;
    private boolean isReConnecting = false;
    private boolean connecting = false;
    private String lastSendContent = "";
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            connect(lastSendContent);
            isReConnecting = false;
        }
    };

    private WebSocketInstance() {
        mClient = new OkHttpClient.Builder()
                .readTimeout(15, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(15, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(15, TimeUnit.SECONDS)//设置连接超时时间
                .pingInterval(15, TimeUnit.SECONDS)
                .build();
//         String time=String.valueOf(System.currentTimeMillis());
//        String host = AppConfigBase.isDebug? "ws://8.129.114.68:8088":"wss://api.tianqifengyun.cn";
//        String token= Md5Util.getInstance().getMD5String(key+"|"+time+"|"+"/ska/match/");
        //       String url=host+"/ska/match/"+time+"/"+token;
//        LogDog.Companion.debug(TAG,"websocket request url:"+url);
        request = new Request.Builder().get().url("wss://kcal-dev.icekredit.ai/ski-backend/audiostream?uid=123456").build();
    }

    public static WebSocketInstance getInstance() {
        if (null == instance) {
            synchronized (WebSocketInstance.class) {
                if (null == instance) {
                    instance = new WebSocketInstance();
                }
            }
        }
        return instance;
    }

    public void connect() {
        connect("");
    }

    public void connect(String message) {
        //开始连接
        if (connecting) {
            return;
        }
        connecting = true;
        webSocket = mClient.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
                //连接成功...
                handler.removeCallbacksAndMessages(null);
                Logcat.d(TAG, "连接成功");
                LogDog.Companion.debug(TAG, "连接成功");
                if (!TextUtils.isEmpty(message)) {
                    send(message);
                }

                connecting = false;

            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
                //收到消息...（一般是这里处理json）
                Logcat.d(TAG, "收到消息:");
                // LogDog.Companion.debug(TAG, "收到消息:" +text);
                MessageResponse messageResponse= JSON.parseObject(text, MessageResponse.class);
                //if(messageResponse.getType()==)
                EventBus.getDefault().post(messageResponse);
                connecting = false;
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                super.onMessage(webSocket, bytes);
                //收到消息...（一般很少这种消息）
                Logcat.d(TAG, "收到消息:ByteString");
                connecting = false;
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                super.onClosed(webSocket, code, reason);
                //连接关闭...
                LogDog.Companion.debug(TAG, "连接关闭:" + reason);
                Logcat.d(TAG, "连接关闭:" + reason);
                connecting = false;
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable throwable, Response response) {
                super.onFailure(webSocket, throwable, response);
                //连接失败...
                connecting = false;
                if (!isReConnecting) {
                    isReConnecting = true;
                    handler.sendEmptyMessageDelayed(0, 3 * 1000);
                }
                Logcat.d(TAG, "连接失败:exception:" + throwable.getMessage());
                LogDog.Companion.debug(TAG, "连接失败:exception:" + throwable.getMessage());
            }
        });
    }


    public boolean send(String message) {
        if (webSocket == null) {
            connect(message);
            return false;
        }
        boolean isSuccess = webSocket.send(message);
        Logcat.d(TAG, isSuccess + "发送消息:" + message);
        LogDog.Companion.debug(TAG, isSuccess + "发送消息:" + message);
        if (isSuccess && !TextUtils.isEmpty(message) && message.indexOf(",") != -1) {
            lastSendContent = message;
        }
        return isSuccess;
    }

    public void cancel() {
        if (null != webSocket) {
            Logcat.d(TAG, "关闭websocket");
            LogDog.Companion.debug(TAG, "关闭websocket");
            webSocket.cancel();
        }
    }

    public String getLastSendContent() {
        return lastSendContent;
    }

    public void setLastSendContent(String lastSendContent) {
        this.lastSendContent = lastSendContent;
    }
}
